package com.photo.note;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.slz.note.R;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.FloatMath;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


public class phototext extends Activity {
   
	private Button but2;
	private EditText edit3;
	private EditText edit4;
	ImageView iv;
	private String photoPath = null;
	SelectPicPopupWindow menuWindow;
	private final String IMAGE_TYPE = "image/*";
	private final int IMAGE_CODE = 0;
	private boolean PorS = false;// 选择图片还是拍照,拍照不压缩图片了;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		 
		 but2=(Button)findViewById(R.id.btn_upPhoto_FBInfo);
		 but2.setOnClickListener(new OnClickListener() {
				@Override
			     public void onClick(View v) {
					
					   edit3= (EditText)findViewById(R.id.headline);
					   edit4= (EditText)findViewById(R.id.content);
					   String headline1=edit3.getText().toString();
					   String content2=edit4.getText().toString();
				}
			});
		 iv = (ImageView) findViewById(R.id.image_xstp_FBInfo);
			iv.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// 实例化SelectPicPopupWindow
					menuWindow = new SelectPicPopupWindow(phototext.this,
							itemsOnClick);
					// 显示窗口
					menuWindow.showAtLocation(
							phototext.this.findViewById(R.id.scrollView1),
							Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置

				}
			});
	}
	// 为弹出窗口实现监听类
		private OnClickListener itemsOnClick = new OnClickListener() {

			public void onClick(View v) {
				menuWindow.dismiss();
				switch (v.getId()) {
				case R.id.btn_take_photo:

					String state = Environment.getExternalStorageState();
					Intent intent;
					if (state.equals(Environment.MEDIA_MOUNTED)) {
						intent = new Intent("android.media.action.IMAGE_CAPTURE");
						startActivityForResult(intent, CONTEXT_RESTRICTED);
					} else {
						Toast.makeText(phototext.this, "未打开相机,可能没找到SD卡",
								Toast.LENGTH_SHORT).show();
					}
					break;
				case R.id.btn_pick_photo:

					Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
					getAlbum.setType(IMAGE_TYPE);
					startActivityForResult(getAlbum, IMAGE_CODE);

					break;
				default:
					break;
				}

			}

		};

		protected Dialog onCreateDialog(int id) {

			return null;
		}
		// 获取图片
		public static Bitmap getLoacalBitmap(String url) {
			try {
				FileInputStream fis = new FileInputStream(url);
				return BitmapFactory.decodeStream(fis);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			}
		}
		// 压缩图片
		@SuppressLint("FloatMath")
		public Bitmap getBitmap(String imageFilePath, int displayWidth,
				int displayHeight) {
			BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
			bitmapOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bitmapOptions);

			// 编码后bitmap的宽高,bitmap除以屏幕宽度得到压缩比
			int widthRatio = (int) FloatMath.ceil(bitmapOptions.outWidth
					/ (float) displayWidth);
			int heightRatio = (int) FloatMath.ceil(bitmapOptions.outHeight
					/ (float) displayHeight);

			if (widthRatio > 1 && heightRatio > 1) {
				if (widthRatio > heightRatio) {
					// 压缩到原来的(1/widthRatios)
					bitmapOptions.inSampleSize = widthRatio;
				} else {
					bitmapOptions.inSampleSize = heightRatio;
				}
			}
			bitmapOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeFile(imageFilePath, bitmapOptions);
			String pictureDir = "";
			FileOutputStream fos = null;
			BufferedOutputStream bos = null;
			ByteArrayOutputStream baos = null;
			try {
				baos = new ByteArrayOutputStream();
				bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				byte[] byteArray = baos.toByteArray();
				String saveDir = Environment.getExternalStorageDirectory()
						+ "/wwjh_small_temp";
				File dir = new File(saveDir);
				if (!dir.exists()) {
					dir.mkdir();
				}
				File file = new File(saveDir, "temp.jpg");
				file.delete();
				if (!file.exists()) {
					file.createNewFile();
				}
				fos = new FileOutputStream(file);
				bos = new BufferedOutputStream(fos);
				bos.write(byteArray);
				pictureDir = file.getPath();
				System.out.println("压缩后存储的地址是:  " + pictureDir);
				photoPath = pictureDir;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (baos != null) {
					try {
						baos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (bos != null) {
					try {
						bos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (fos != null) {
					try {
						fos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			return bmp;
		}


		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			Bitmap photo = null;
			try {
				if (requestCode == CONTEXT_RESTRICTED) {
					Uri uri = data.getData();
					if (uri != null) {
						photo = BitmapFactory.decodeFile(uri.getPath());
					}
					if (photo == null) {
						Bundle bundle = data.getExtras();
						if (bundle != null) {
							photo = (Bitmap) bundle.get("data");
						} else {
							Toast.makeText(phototext.this, "接受失败",
									Toast.LENGTH_LONG).show();
							return;
						}
					}
					String pictureDir = "";
					FileOutputStream fos = null;
					BufferedOutputStream bos = null;
					ByteArrayOutputStream baos = null;
					try {
						baos = new ByteArrayOutputStream();
						photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
						byte[] byteArray = baos.toByteArray();
						String saveDir = Environment.getExternalStorageDirectory()
								+ "/temple";
						File dir = new File(saveDir);
						if (!dir.exists()) {
							dir.mkdir();
						}
						File file = new File(saveDir, "temp.jpg");
						file.delete();
						if (!file.exists()) {
							file.createNewFile();
						}
						fos = new FileOutputStream(file);
						bos = new BufferedOutputStream(fos);
						bos.write(byteArray);
						pictureDir = file.getPath();
						System.out.println("拍照后存储的地址是:  " + pictureDir);
						photoPath = pictureDir;
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						if (baos != null) {
							try {
								baos.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						if (bos != null) {
							try {
								bos.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						if (fos != null) {
							try {
								fos.close();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (resultCode != RESULT_OK) { // 此处的 RESULT_OK 是系统自定义得一个常量
				// Log.e(TAG,"ActivityResult resultCode error");
				System.out.println("这是个啥?");
				return;
			}

			ContentResolver resolver = getContentResolver();
			if (requestCode == IMAGE_CODE) {
				PorS = true;
				try {
					@SuppressWarnings("unused")
					Bitmap bm = null;
					Uri originalUri = data.getData(); // 获得图片的uri
					bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片
					// 这里开始的第二部分，获取图片的路径：
					String[] proj = { MediaStore.Images.Media.DATA };
					@SuppressWarnings("deprecation")
					Cursor cursor = managedQuery(originalUri, proj, null, null,
							null);
					// 按我个人理解 这个是获得用户选择的图片的索引值
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					// 最后根据索引值获取图片路径
					photoPath = cursor.getString(column_index);
					System.out.println("图片的路径是::" + photoPath);
					Log.e("Lostinai", photoPath);

				} catch (IOException e) {

					Log.e("Lostinai", e.toString());

				}

			}
			Bitmap tem = null;
			if (PorS) {
				tem = getBitmap(photoPath, 200, 200);
			} else {
				tem = getLoacalBitmap(photoPath);
			}
			iv.setImageBitmap(tem);
		}


}
